package com.nbjtjc.safe.service.index;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.mapper.danger.DangerInspectListPublicMapper;
import com.nbjtjc.safe.mapper.danger.DangerInspectPublicMapper;
import com.nbjtjc.safe.mapper.emg.EmgPlanPublicMapper;
import com.nbjtjc.safe.mapper.emg.handle.EmgHandlePublicMapper;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.model.danger.DangerInspectListPublic;
import com.nbjtjc.safe.model.sys.SysDept;
import com.nbjtjc.safe.service.cost.FrontPageService;
import com.nbjtjc.safe.service.sys.SysDeptService;
import com.nbjtjc.safe.util.DateUtils;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @auther guqianbin
 * @date 2018/7/16 13:58
 **/
@Service("safeIndexService")
public class IndexService {
    @Autowired
    private DangerInspectListPublicMapper dangerInspectListPublicMapper;

    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private DangerInspectPublicMapper dangerInspectPublicMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private EmgHandlePublicMapper emgHandlePublicMapper;
    @Autowired
    private EmgPlanPublicMapper emgPlanPublicMapper;
    @Autowired
    private FrontPageService frontPageService;

    @Autowired
    private TaskService taskService;

    /**
     * 首页的四种任务的数量
     *
     * @return
     */
    public Map<String, Integer> indexTaskInfo(int year) {
        Map<String, Integer> data = new HashMap<>();
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(MyShiroUtils.getSessionUserId().toString())
                .list();
        data.put("todayCount", tasks.size());
        return data;
    }

    /**
     * 年度安全概括
     *
     * @param year
     * @return
     */
    public Map<String, Object> yearSafeSummary(int year) throws ParseException {
        Map<String, Object> data = new HashMap<>();
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(MyShiroUtils.getCompanyId());
        List<SysDept> sysDepts = new ArrayList<>();
        List<SysDept> tempDepts = sysDeptService.getCompanyDepts(sysDept, false, sysDepts);
        if (CollectionUtil.isEmpty(tempDepts)) {
            return data;
        }
        List<Integer> sysDeptIds = sysDepts.parallelStream()
                .map(SysDept::getId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(sysDeptIds)) {
            return data;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date yeard = sdf.parse(year + "");
        data.put("dangerIndexInfo", dangerIndexInfo(year, sysDeptIds));
        data.put("emgIndexInfo", emgInfo(year, sysDeptIds));
        data.put("eduInfo", frontPageService.eduCondition(yeard));
        data.put("safeInfo", frontPageService.costCondition(yeard));
        return data;

    }

    /**
     * 安全警示趋势 按年份和月份来统计显示，当前年份，去年的年份
     *
     * @param year
     * @return
     */
    public Map<String, Object> safeWarningTrend(int year) {
        Map<String, Object> data = new HashMap<>();
        List<Date> yearRange = DateUtils.getYearRange(year);
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(MyShiroUtils.getCompanyId());
        List<SysDept> sysDepts = new ArrayList<>();
        List<SysDept> tempDepts = sysDeptService.getCompanyDepts(sysDept, false, sysDepts);
        if (CollectionUtil.isEmpty(tempDepts)) {
            return data;
        }
        List<Integer> sysDeptIds = sysDepts.parallelStream()
                .map(SysDept::getId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(sysDeptIds)) {
            return data;
        }
        sysDeptIds.add(MyShiroUtils.getCompanyId());
        List<Integer> dangerInspectPublicIds = dangerInspectPublicMapper
                .findDangerInspectIdsByDeptId(sysDeptIds, yearRange.get(0), yearRange.get(1));
        if (CollectionUtil.isEmpty(dangerInspectPublicIds)) {
            return data;
        }
        DangerInspectListPublic dangerInspectListPublic = new DangerInspectListPublic();
        dangerInspectListPublic.setDangerInspectPublicIds(dangerInspectPublicIds);
        List<DangerInspectListPublic> dangerInspectListPublics = dangerInspectListPublicMapper.search(dangerInspectListPublic);
        if (CollectionUtil.isEmpty(dangerInspectListPublics)) {
            return data;
        }

        Map<Integer, Integer> monthCount = new HashMap<>();
        initMonthMap(monthCount);
        dangerInspectListPublics.forEach(inspectList -> {
            if (ObjectUtil.isNotNull(inspectList.getNeedChange())
                    && inspectList.getNeedChange().equals(1)) {
                int month = inspectList.getCreateTime().toInstant()
                        .atZone(ZoneId.systemDefault()).toLocalDate().getMonthValue();
                if (!monthCount.containsKey(month)) {
                    monthCount.put(month, 1);
                } else {
                    monthCount.put(month, monthCount.get(month) + 1);
                }
            }
        });
        data.put(year + "", monthCount);
        return data;
    }

    private void initMonthMap(Map<Integer, Integer> monthCount) {
        for (int i = 1; i <= 12; i++) {
            monthCount.put(i, 0);
        }
    }

    /**
     * 隐患统计分析，按类型，隐患等级，按整改状态，控股公司
     *
     * @param year
     * @return
     */
    public Map<String, Object> analysisHiddenDangers(int year) {
        Map<String, Object> data = new HashMap<>();
        List<Date> yearRangeDate = DateUtils.getYearRange(year);

        List<Integer> sysDeptIds = sysDeptService.getSubDeptAndCompanyIds(MyShiroUtils.getCompanyId());
        List<Integer> dangerInspectPublicIds = dangerInspectPublicMapper
                .findDangerInspectIdsByDeptId(sysDeptIds, yearRangeDate.get(0)
                        , yearRangeDate.get(1));
        if (CollectionUtil.isEmpty(dangerInspectPublicIds)) {
            return data;
        }
        DangerInspectListPublic dangerInspectListPublic = new DangerInspectListPublic();
        dangerInspectListPublic.setDangerInspectPublicIds(dangerInspectPublicIds);
        dangerInspectListPublic.setNeedChange(1);
        /*List<DangerInspectListPublic> dangerInspectListPublics =
                dangerInspectListPublicMapper.search(dangerInspectListPublic);*/
        //TODO 去掉级联查询
        List<DangerInspectListPublic> dangerInspectListPublics =
                dangerInspectListPublicMapper.searchNoAssociateUserName(dangerInspectListPublic);
        if (CollectionUtil.isEmpty(dangerInspectListPublics)) {
            return data;
        }
        Map<Integer, Set<Integer>> subCompanyDeptIds = new HashMap<>();
        //获取当前公司的控股公司id
        List<SysDept> subCompany = sysDeptMapper.getSubCompanyByParentId(MyShiroUtils.getCompanyId(),
                Constant.SysDeptType.COMPANY.getValue());
        if (CollectionUtil.isNotEmpty(subCompany)) {
        }
        Map<String, Integer> level = new HashMap<>();
        Map<String, Integer> dangerType = new HashMap<>();
        Map<String, Integer> dangerFinishStatus = new HashMap<>();
        initDangerFinishStatusMap(dangerFinishStatus);
        dangerInspectListPublics.forEach(inspectList -> {
            if (ObjectUtil.isNotNull(inspectList.getHiddenDangerLevel())) {
                String dangerLevel = inspectList.getHiddenDangerLevel();
                if (level.containsKey(dangerLevel)) {
                    level.put(dangerLevel
                            , level.get(dangerLevel) + 1);
                } else {
                    level.put(dangerLevel, 1);
                }
            }
            if (ObjectUtil.isNotNull(inspectList.getDangerType())) {
                String hiddenDangerType = inspectList.getDangerType();
                if (dangerType.containsKey(hiddenDangerType)) {
                    dangerType.put(hiddenDangerType, dangerType.get(hiddenDangerType) + 1);
                } else {
                    dangerType.put(hiddenDangerType, 1);
                }
            }

            if(ObjectUtil.isNotNull(inspectList.getChangeTime())){
                dangerFinishStatus.put("已整改", dangerFinishStatus.get("已整改") + 1);
            }else{
                //TODO 加上督办整改
                if (ObjectUtil.isNotNull(inspectList.getDeadline())&&inspectList.getDeadline().before(new Date())) {
                    dangerFinishStatus.put("超期未整改", dangerFinishStatus.get("超期未整改") + 1);
                }else{
                    dangerFinishStatus.put("待整改", dangerFinishStatus.get("待整改") + 1);
                }
            }
            //整改超期或者没有完成的

            //有整改结束时间，有督办期限，但是没有督办结束时间的，
//            if (ObjectUtil.isNotNull(inspectList.getSuperviseFinishDate())
//                    && ObjectUtil.isNotNull(inspectList.getChangeTime())
//                    && ObjectUtil.isNull(inspectList.getSuperviseReformDate())) {
//                dangerFinishStatus.put("待整改", dangerFinishStatus.get("待整改") + 1);
//            }

        });
        data.put("dangerLevel", level);
        data.put("dangerType", dangerType);
        data.put("dangerStatus", dangerFinishStatus);
        return data;
    }

    private void initDangerFinishStatusMap(Map<String, Integer> dangerFinishStatus) {
        dangerFinishStatus.put("已整改", 0);
        dangerFinishStatus.put("待整改", 0);
        dangerFinishStatus.put("超期未整改", 0);
    }


    private Map<String, Integer> dangerIndexInfo(int year, List<Integer> sysDeptIds) {
        List<Date> yearRange = DateUtils.getYearRange(year);

        Map<String, Integer> data = new HashMap<>();
        data.put("dangerCount", 0);
        data.put("dangerInspectCount", 0);
        data.put("dangerReformCount", 0);
        data.put("dangerUnReformCount", 0);

        sysDeptIds.add(MyShiroUtils.getCompanyId());
        List<Integer> dangerInspectPublicIds = dangerInspectPublicMapper
                .findDangerInspectIdsByDeptId(sysDeptIds, yearRange.get(0), yearRange.get(1));
        if (CollectionUtil.isEmpty(dangerInspectPublicIds)) {
            return data;
        }
        data.put("dangerInspectCount", dangerInspectPublicIds.size());
        DangerInspectListPublic dangerInspectListPublic = new DangerInspectListPublic();
        dangerInspectListPublic.setDangerInspectPublicIds(dangerInspectPublicIds);
//        List<DangerInspectListPublic> dangerInspectListPublics = dangerInspectListPublicMapper.search(dangerInspectListPublic);

        List<DangerInspectListPublic> dangerInspectListPublics =
                dangerInspectListPublicMapper.findByDangerInspectPublicId(dangerInspectPublicIds);
        if (CollectionUtil.isEmpty(dangerInspectListPublics)) {
            return data;
        }
        data.put("validCount", 0);

        dangerInspectListPublics.forEach(inspectList -> {
            if (ObjectUtil.isNotNull(inspectList.getNeedChange())
                    && inspectList.getNeedChange().equals(1)) {
                data.put("dangerCount", data.get("dangerCount") + 1);
                //整改已经完成的
                //有整改结束时间，但是没有督办期限的就是已经整改完的
                if (ObjectUtil.isNotNull(inspectList.getChangeTime())) {
                    data.put("dangerReformCount", data.get("dangerReformCount") + 1);
                } else {
                    data.put("dangerUnReformCount", data.get("dangerUnReformCount") + 1);
                }


            }
        });
        return data;
    }

    private Map<String, Integer> emgInfo(int year, List<Integer> sysDeptIds) {
        Map<String, Integer> data = new HashMap<>();
        List<Date> yearRange = DateUtils.getYearRange(year);

        int emgPlanPublicCount = emgPlanPublicMapper
                .selectEmgPlanPublicCountByDeptIds(sysDeptIds, yearRange.get(0),
                        yearRange.get(1));
        data.put("emgPlanPublicCount", emgPlanPublicCount);
        int emgHandleCount = emgHandlePublicMapper.selectHandlePublicCountByDeptIds(sysDeptIds,
                yearRange.get(0), yearRange.get(1));
        data.put("emgHandlePublicCount", emgHandleCount);

        return data;
    }
}
